package com.qf.lanzhou.blog.api.controller;

import com.qf.lanzhou.blog.api.pojo.entity.Praise;
import com.qf.lanzhou.blog.api.pojo.entity.User;
import com.qf.lanzhou.blog.api.service.PraiserInsertService;
import com.qf.lanzhou.blog.api.service.impl.PraiserInsertServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author jian   添加点赞功能
 * @Date 2020/12/17 14:55
 * @JDK 1.8
 * @Version 1.0
 */
@WebServlet("/InsertPraise.do")
public class PraiseInsertServlet extends BaseServletPost{
    private PraiserInsertService pinsert=new PraiserInsertServiceimpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决请求的乱码
        req.setCharacterEncoding("utf-8");
        //解决响应乱码
        resp.setContentType("text/html;charset=utf-8");

        //获取参数,用户id,文章id
        User user1 = (User) req.getSession().getAttribute("user");
        Long id = user1.getId();
        //转为string类型
        String userId = id + "";
        String articleId = req.getParameter("articleId");
        String praiseStatus = req.getParameter("priceStatus");
        //判断用户是否有登录
        User user = (User) req.getSession().getAttribute("user");



        //查询该名用户是否已经对这篇文章点赞成功了,点赞过,提醒用户已经点赞过了
        List<Praise> list = pinsert.selectPraiser(userId,articleId,praiseStatus);
        for (int j = 0; j<list.size() ; j++) {
            Praise praise = list.get(j);
            System.out.println(praise);

            if(userId.equals(praise.getUserId())&&articleId.equals(praise.getArticleId())&&praiseStatus.equals(praise.getPraiseStatus())){
                resp.getWriter().write("已点赞过");
                return;
            }
        }
        if (pinsert.checkPraiser(userId,articleId)==null){
            int i = pinsert.addPraiser(userId, articleId, praiseStatus);
            if(i==1){
                successResultWrite("添加成功",resp);
                return;
            }
            return ;
        }
        try{
            pinsert.praise(userId, articleId);
            successResultWrite("点赞成功",resp);
        }catch (RuntimeException e){
            String message = e.getMessage();
            failedResultWrite(message,resp);
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
